package com.designmode.单例模式;

/**
 * 懒汉式单例
 */
public class LazyMan {


//    DCL


    private LazyMan() {

        System.out.println(Thread.currentThread().getName());
    }

    public static LazyMan lazyMan;

    public static LazyMan getInstance() {

        //加锁 双重检测锁 懒汉式单例 DCL懒汉式
        if (lazyMan == null) {
            synchronized (LazyMan.class) {
                if (lazyMan == null) {
                    lazyMan = new LazyMan(); //不是一个原子性操作


                    /**
                     * 1 分配内存空间
                     * 2 执行构造方法，初始化对象
                     * 3 把对象指向这个空间
                     *
                     *
                     *
                     * 123
                     * 132
                     *
                     * 此时lazyMan还没有完成构造
                     */
                }
            }
        }
        if (lazyMan == null) {
            lazyMan = new LazyMan();
        }
        return lazyMan; //此时lazyM
    }

//单线程下单例ok

    public static void main(String[] args) {
        for (int i = 0; i < 10; i++) {
            new Thread(() -> {
                LazyMan.getInstance();
            }).start();
        }
    }

}



